package com.traffic.between.service;

import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.xml.rpc.ParameterMode;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.traffic.between.config.BetweenProperties;
import com.traffic.between.util.Xml2JsonUtil;

import net.sf.json.JSONObject;

public class GjmyServiceImpl {
	private static Logger logger = Logger.getLogger(GjmyServiceImpl.class);
	public static GjmyServiceImpl service = new GjmyServiceImpl();

	private static String HOST_ORDER_PATH = BetweenProperties.GJMY_ORDER_URL;
	private static String HOST_ORDERSTATUS_PATH = BetweenProperties.GJMY_ORDERSTATUS_URL;
	private static String GJMY_APPKEY = BetweenProperties.GJMY_APPKEY;
	private static String GJMY_SECURITYKEY = BetweenProperties.GJMY_SECURITYKEY;

	public String order(String productId, String phoneNo, String cstmOrderNo) {
		String res="";
		Gson gson = new Gson();
		Map<String, String> paramMap = new HashMap<String, String>();
		
		try { 
			  
            Service service = new Service();  
            Call call = (Call) service.createCall();  
            call.setTargetEndpointAddress(HOST_ORDER_PATH);  
            // WSDL里面描述的接口名称(要调用的方法)  
            call.setOperationName("InterFlowbackOpen");  
            // 接口方法的参数名, 参数类型,参数模式  IN(输入), OUT(输出) or INOUT(输入输出)  
            call.addParameter("pkey", XMLType.XSD_STRING, ParameterMode.IN);  
            call.addParameter("seqId", XMLType.XSD_STRING, ParameterMode.IN);  
            call.addParameter("loginName", XMLType.XSD_STRING, ParameterMode.IN);  
            call.addParameter("phoneNo", XMLType.XSD_STRING, ParameterMode.IN); 
            call.addParameter("productCode", XMLType.XSD_STRING, ParameterMode.IN);
            call.addParameter("startTime", XMLType.XSD_STRING, ParameterMode.IN); 
            call.addParameter("endTime", XMLType.XSD_STRING, ParameterMode.IN);
            call.addParameter("code", XMLType.XSD_STRING, ParameterMode.IN);
            
            Date dBefore = new Date();
    		Calendar calendar = Calendar.getInstance(); //得到日历
    		calendar.add(Calendar.DAY_OF_MONTH, +1);  //设置为后一天
    		dBefore = calendar.getTime();   //得到后一天的时间
    		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd"); //设置时间格式
    		String startTime = sdf.format(dBefore);    //格式化后一天
    		String endTime = sdf.format(dBefore);
            
            //升序endTime loginName phoneNo pkey productCode seqId startTime
            String str =startTime+cstmOrderNo+productId+GJMY_APPKEY+phoneNo+"szypxgj"+endTime+GJMY_SECURITYKEY;
    		String code = getMD5(str);
            // 设置被调用方法的返回值类型  
            call.setReturnType(XMLType.XSD_STRING); 
            
            //设置方法中参数的值  
            Object[] paramValues = new Object[] {GJMY_APPKEY,cstmOrderNo,"szypxgj",phoneNo,productId,startTime,endTime,code};  
            // 给方法传递参数，并且调用方法  
            res = (String) call.invoke(paramValues);    
      
            String body = Xml2JsonUtil.xml2JSON(res);
            logger.info("between- 国际漫游流量订购请求时响应结果  " + body);
			JSONObject resultJson = JSONObject.fromObject(body);
			JSONObject json = (JSONObject) resultJson.get("AgentRsp");
			String resultCode = json.getString("ResultCode");
			String resultDesc = json.getString("ResultDesc");
			
				if ("0".equals(resultCode)) {
					paramMap.put("resultCode", "00");
					paramMap.put("resultDesc", resultDesc);
					res = gson.toJson(paramMap);
				}else {
					paramMap.put("resultCode", "01");
					paramMap.put("resultDesc", resultDesc);
					res = gson.toJson(paramMap);
				}
        } catch (Exception e) {  
            logger.error("between- 国际漫游流量订购请求时的响应异常: " + e);       	
        }
		logger.info("between- 国际漫游流量订购请求时的响应:" +res+",cstmOrderNo:"+cstmOrderNo);
		return res;
	}

	public String orderStatus(String cstmOrderNo) {

		String res="";
		Gson gson = new Gson();
		Map<String, String> paramMap = new HashMap<String, String>();
		try {  
			  
            //String endpoint = "http://211.95.193.67/axis/services/IMBackwardProductService?wsdl";  
  
            Service service = new Service();  
            Call call = (Call) service.createCall();  
            call.setTargetEndpointAddress(HOST_ORDERSTATUS_PATH);  
            // WSDL里面描述的接口名称(要调用的方法)  
            call.setOperationName("orderResult");  
            // 接口方法的参数名, 参数类型,参数模式  IN(输入), OUT(输出) or INOUT(输入输出)  
            call.addParameter("pkey", XMLType.XSD_STRING, ParameterMode.IN);  
            call.addParameter("seqId", XMLType.XSD_STRING, ParameterMode.IN);  
            call.addParameter("code", XMLType.XSD_STRING, ParameterMode.IN);
            
            //按参数名降序排列顺序为： seqId, productCode, pkey, phoneNo , loginName
            String str =cstmOrderNo+GJMY_APPKEY+ GJMY_SECURITYKEY;
    		String sign = getMD5(str);
            // 设置被调用方法的返回值类型  
            call.setReturnType(XMLType.XSD_STRING); 
            
            //设置方法中参数的值  
            Object[] paramValues = new Object[] {GJMY_APPKEY,cstmOrderNo,sign};  
            // 给方法传递参数，并且调用方法  
            res = (String) call.invoke(paramValues);    
      
            String body = Xml2JsonUtil.xml2JSON(res);
			JSONObject resultJson = JSONObject.fromObject(body);
			JSONObject json = (JSONObject) resultJson.get("AgentRsp");
			String resultCode = json.getString("ResultCode");
			String resultDesc = json.getString("ResultDesc");
			logger.info("between- 国际漫游流量查询状态返回:" +body);
				if ("0".equals(resultCode)) {
					paramMap.put("resultCode","00");
					paramMap.put("resultDesc",resultDesc);
					res = gson.toJson(paramMap);
				}else if("9".equals(resultCode) || "11".equals(resultCode)||"1".equals(resultCode)){
					paramMap.put("resultCode","02");
					paramMap.put("resultDesc",resultDesc);
					res = gson.toJson(paramMap);
				}else {
					paramMap.put("resultCode","01");
					paramMap.put("resultDesc",resultDesc);
					res = gson.toJson(paramMap);
				}                                
        } catch (Exception e) {  
            logger.error("between- 国际漫游流量订购请求时的响应异常: " + e);
            paramMap.put("resultCode","02");
			paramMap.put("resultDesc","查询异常，请稍后");
			logger.info("between- 国际漫游流量查询状态返回:" +gson.toJson(paramMap)+",cstmOrderNo:"+cstmOrderNo);
			res = gson.toJson(paramMap);
        }
		logger.info("between- 国际漫游流量查询状态返回:" +res +",cstmOrderNo:"+cstmOrderNo);
		return res;

	}
	
	public static String getMD5(String message) {
		MessageDigest messageDigest = null;
		StringBuffer md5StrBuff = new StringBuffer();
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(message.getBytes("UTF-8"));

			byte[] byteArray = messageDigest.digest();
			for (int i = 0; i < byteArray.length; i++) {
				if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
					md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
				else
					md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
			}
		} catch (Exception e) {
			throw new RuntimeException();
		}
		return md5StrBuff.toString().toUpperCase();// 字母大写
	}
	
	public static void main(String[] args) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("seqId", "");//seqId, productCode, pkey, phoneNo , loginName
		params.put("productCode", "");//seqId, productCode, pkey, phoneNo , loginName
		params.put("pkey", "");//seqId, productCode, pkey, phoneNo , loginName
		params.put("phoneNo", "");//seqId, productCode, pkey, phoneNo , phoneNo
		params.put("startTime", "");//seqId, productCode, pkey, phoneNo , loginName
		params.put("endTime", "");//seqId, productCode, pkey, phoneNo , loginName
		params.put("loginName", "");//seqId, productCode, pkey, phoneNo , loginName
		Object[] keys = params.keySet().toArray();
		Arrays.sort(keys);//升序
		for (Object key : keys) {
			System.out.println(key);
		}

		//endTime loginName phoneNo pkey productCode seqId startTime
	}}
